package cn.com.shadowless.xinning.view.fragment;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mengpeng.mphelper.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.CarNoInfo;
import cn.com.shadowless.xinning.model.order.CarOrderInfo;
import cn.com.shadowless.xinning.model.order.CheckHistoryList;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.Item;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;

/**
 * The type Car fragment.
 *
 * @author sHadowLess
 */
public class CarFragment extends BaseFragment {

    /**
     * The Car order num.
     */
    @BindView(R.id.car_orderNum)
    TextView carOrderNum;
    /**
     * The Car make time.
     */
    @BindView(R.id.car_makeTime)
    TextView carMakeTime;

    /**
     * The Car is go out.
     */
    @BindView(R.id.car_isGoOut)
    TextView carIsGoOut;

    /**
     * The Car maker.
     */
    @BindView(R.id.car_maker)
    TextView carMaker;
    /**
     * The Car make depart.
     */
    @BindView(R.id.car_makeDepart)
    TextView carMakeDepart;
    /**
     * The Car position.
     */
    @BindView(R.id.car_position)
    TextView carPosition;
    /**
     * The Car applier.
     */
    @BindView(R.id.car_applier)
    TextView carApplier;
    /**
     * The Car apply depart.
     */
    @BindView(R.id.car_applyDepart)
    TextView carApplyDepart;
    /**
     * The Car use date.
     */
    @BindView(R.id.car_useDate)
    TextView carUseDate;
    /**
     * The Car user num.
     */
    @BindView(R.id.car_userNum)
    TextView carUserNum;
    /**
     * The Car expected go time.
     */
    @BindView(R.id.car_expectedGoTime)
    TextView carExpectedGoTime;
    /**
     * The Car expected back time.
     */
    @BindView(R.id.car_expectedBackTime)
    TextView carExpectedBackTime;
    /**
     * The Car go local.
     */
    @BindView(R.id.car_GoLocal)
    TextView carGoLocal;
    /**
     * The Car arrive local.
     */
    @BindView(R.id.car_ArriveLocal)
    TextView carArriveLocal;
    /**
     * The Car replenishment.
     */
    @BindView(R.id.car_replenishment)
    TextView carReplenishment;
    /**
     * The Car use type.
     */
    @BindView(R.id.car_useType)
    TextView carUseType;
    /**
     * The Car driver name.
     */
    @BindView(R.id.car_driverName)
    TextView carDriverName;
    /**
     * The Car card no.
     */
    @BindView(R.id.car_cardNo)
    TextView carCardNo;
    /**
     * The Car driver phone.
     */
    @BindView(R.id.car_driverPhone)
    TextView carDriverPhone;
    /**
     * The Car check process.
     */
    @BindView(R.id.car_check_process)
    LinearLayout carCheckProcess;
    /**
     * The Car use car reason.
     */
    @BindView(R.id.car_useCarReason)
    TextView carUseCarReason;


    private final String url = "api/UseCarApply/LoadCheckHistoryList?%s=";
    /**
     * The List.
     */
    List<Item> list = new ArrayList<>();
    private Handler handler;

    /**
     * Instantiates a new Car fragment.
     *
     * @param handler the handler
     */
    public CarFragment(Handler handler) {
        this.handler = handler;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            initCarderInfo(orderId, userName);
            initCarNoInfo("", "", "1", "2", userName);
            initCarCheckHistoryList(String.format(url, "orderId") + orderId, mActivity, carCheckProcess);
        }
    }

    private void initCarderInfo(String orderId, String userName) {
        OrderPresenter
                .getSingleton()
                .getCarOrderInfo(orderId, userName, new RequestCallBack<CarOrderInfo>() {
                    @Override
                    public void success(RequestResult<CarOrderInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (result.isSucceed() && null != result.getResult()) {
                            if (null != token && token.equals(oldToken)) {
                                Log.e(TAG, "success: " + result.toString());
                                CarOrderInfo.DataBean dataBean = result.getResult().getData();
                                String id = dataBean.getId();
                                String createTimeString = dataBean.getCreateTimeString();
                                String makeOrderUser = dataBean.getMakeOrderUser();
                                String makeDepartment = dataBean.getMakeDepartment();
                                String makePosition = dataBean.getMakePosition();
                                carOrderNum.setText(id);
                                carMakeTime.setText(createTimeString);
                                carMaker.setText(makeOrderUser);
                                carMakeDepart.setText(makeDepartment);
                                carPosition.setText(makePosition);

                                String proposerName = dataBean.getProposerName();
                                String departmentName = dataBean.getDepartmentName();
                                String useCarDateString = dataBean.getUseCarDateString();
                                String carNumber = dataBean.getCarNumber() + "";
                                String predictOutTime = dataBean.getPredictOutTime();
                                String predictBackTime = dataBean.getPredictBackTime();
                                String outAddress = dataBean.getOutAddress();
                                String destination = dataBean.getDestination();
                                String useCarReasons = dataBean.getUseCarReasons();
                                boolean isRepairOrder = dataBean.isRepairOrder();
                                String useCarType = dataBean.getUseCarType();
                                String driverName = dataBean.getDriverName();
                                String carNo = dataBean.getCarNo();
                                String driverPhone = dataBean.getDriverPhone();
                                String isOutCityStr = dataBean.getIsOutCityStr();
                                carIsGoOut.setText(isOutCityStr);
                                carApplier.setText(proposerName);
                                carApplyDepart.setText(departmentName);
                                carUseDate.setText(useCarDateString);
                                carUserNum.setText(carNumber);
                                carExpectedGoTime.setText(predictOutTime);
                                carExpectedBackTime.setText(predictBackTime);
                                carGoLocal.setText(outAddress);
                                carArriveLocal.setText(destination);
                                carUseCarReason.setText(useCarReasons);
                                if (isRepairOrder) {
                                    carReplenishment.setText("√ 补单");
                                } else {
                                    carReplenishment.setText("X 不补单");
                                }
                                carUseType.setText(useCarType);
                                carDriverName.setText(driverName);
                                carCardNo.setText(carNo);
                                carDriverPhone.setText(driverPhone);
                            } else {
                                ToastUtils.onErrorShowToast("登录态与服务器不一致");
                                initLogoutInfo(mActivity, userName);
                            }
                        } else {
                            ToastUtils.onErrorShowToast("暂无订单列表");
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }

    private void initCarNoInfo(String carNo, String driverName, String pageIndex, String usage, String userName) {
        OrderPresenter
                .getSingleton()
                .getCarNoInfo(carNo, driverName, pageIndex, usage, userName, new RequestCallBack<CarNoInfo>() {
                    @Override
                    public void success(RequestResult<CarNoInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (token.equals(oldToken)) {
                            if (null != result.getResult() && result.isSucceed()) {
                                list.clear();
                                List<CarNoInfo.DataBean> dataBeans = result.getResult().getData();
                                for (CarNoInfo.DataBean dataBean : dataBeans) {
                                    String carNo = dataBean.getCarNo();
                                    list.add(new Item(carNo));
                                }
                                Message message = Message.obtain(handler);
                                message.obj = list;
                                message.what = 1;
                                handler.sendMessage(message);
                            } else {
                                ToastUtils.onErrorShowToast("该订单暂无详细信息");
                            }
                        } else {
                            ToastUtils.onErrorShowToast("登录态与服务器不一致");
                            initLogoutInfo(mActivity, userName);
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }

    private void initCarCheckHistoryList(String url, Activity mActivity, LinearLayout mLinearLayout) {
        String userName = PreferencesUtils.getString(MyApplication.getInstance(), "userName", "-1");
        OrderPresenter.getSingleton().getCheckHistoryList(url, userName, new RequestCallBack<CheckHistoryList>() {
            @Override
            public void success(RequestResult<CheckHistoryList> result) {
                String token = result.getLoginToken();
                String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                if (result.isSucceed() && null != result.getResult()) {
                    if (null != token && token.equals(oldToken)) {
                        Log.e(TAG, "success: " + result.toString());
                        List<CheckHistoryList.DataBean> dataBean = result.getResult().getData();
                        for (int i = 0; i < dataBean.size(); i++) {
                            String localUserName = PreferencesUtils.getString(MyApplication.getInstance(), "userName");
                            String checkAccount = dataBean.get(i).getCheckAccount();
                            if (checkAccount.equals(localUserName)) {
                                int seq = dataBean.get(i).getSeq();
                                String checkStatus = dataBean.get(i).getStatus();
                                if (seq == 1 && checkStatus.equals("CS020")) {
                                    handler.sendEmptyMessage(2);
                                }
                            }
                            View view = LayoutInflater.from(mActivity).inflate(R.layout.fragment_order_process_item, null, false);
                            LinearLayout linearLayout = view.findViewById(R.id.general_check_Process_Item);
                            TextView time = view.findViewById(R.id.general_check_Process_Time);
                            TextView link = view.findViewById(R.id.general_check_Process_Link);
                            TextView name = view.findViewById(R.id.general_check_Process_Name);
                            TextView status = view.findViewById(R.id.general_check_Process_Status);
                            String checkTimeStr = dataBean.get(i).getCheckTimeStr();
                            String checkAccountUserName = dataBean.get(i).getCheckAccountUserName();
                            String processName = dataBean.get(i).getProcessName();
                            String statusStr = dataBean.get(i).getStatusStr();
                            time.setText(checkTimeStr);
                            name.setText(String.format("%s(%s)", checkAccountUserName, processName));
                            status.setText(statusStr);
                            if ("待审核".equals(statusStr)) {
                                time.setTextColor(Color.parseColor("#4a80ef"));
                                link.setTextColor(Color.parseColor("#4a80ef"));
                                name.setTextColor(Color.parseColor("#4a80ef"));
                                status.setTextColor(Color.parseColor("#4a80ef"));
                            }
                            mLinearLayout.addView(linearLayout);
                        }
                    } else {
                        ToastUtils.onErrorShowToast("错误代码：" + result.getErrorCode() + "\n错误信息：" + result.getRemark());
                        initLogoutInfo(mActivity, userName);
                    }
                } else {
                    ToastUtils.onErrorShowToast("暂无审批流程信息");
                }
            }

            @Override
            public void fail(String errorMsg) {
                ToastUtils.onErrorShowToast(errorMsg);
            }
        });
    }

    @Override
    protected void initView() {

    }
}
